package com.fengyunhe.manager.web;

import com.fengyunhe.common.RequestThread;
import com.fengyunhe.manager.UserStatus;
import com.fengyunhe.common.AppContext;
import com.fengyunhe.common.bean.TreeNode;
import com.fengyunhe.manager.AdminLog;
import com.fengyunhe.manager.CurrentUser;
import com.fengyunhe.manager.service.AdminUserService;
import com.fengyunhe.manager.vo.AdminUserVo;
import com.fengyunhe.utils.ip.RequestIP;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台管理门面
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/admin")
@Order(2)
public class AdminController extends AdminBaseController {

    static final String MODULE_NAME = "后台";


    @Autowired
    private AdminUserService adminUserService;


    /**
     * 登录页面
     *
     * @return
     */
    @RequestMapping(value = "/login.do", method = RequestMethod.GET)
    public String adminLogin() {
        return "/index";
    }

    /**
     * 管理登录
     *
     * @param username
     * @param password
     * @return
     * @throws java.io.IOException
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public Map<String, Object> adminLogin(String username, String password, String captcha) {
        HttpServletRequest request = RequestThread.getRequest();
        HttpServletResponse response = RequestThread.getResponse();
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isEmpty(username)) {
            map.put("msg", "用户名或密码错误，请重新输入");
            map.put("success", false);
            return map;
        }
        Subject subject = SecurityUtils.getSubject();
        Object attribute = subject.getSession().getAttribute(AppContext.getCaptchaKey());
        subject.getSession().removeAttribute(AppContext.getCaptchaKey());
        if (attribute == null || captcha == null ||  !captcha.equalsIgnoreCase(attribute.toString())) {
            map.put("msg", "验证码错误");
            map.put("success", false);
            return map;
        }
        AuthenticationToken token = new UsernamePasswordToken(username, username + password + username, false);
        if (!subject.isAuthenticated()) {
            try {
                subject.login(token);
            } catch (AuthenticationException e) {
                map.put("msg", "用户名或密码错误");
                map.put("success", false);
                return map;
            }
        }


        AdminUserVo user = this.adminUserService.getAdminUserByLoginName(username);

        if (user.getStatus() == UserStatus.DISABLED_STATUS) {
            subject.logout();
            map.put("msg", "帐号已停用，无法登录");
            map.put("success", false);
            return map;
        }
        CurrentUser currentUser = new CurrentUser();
        currentUser.setDisplayName(user.getNickname());
        currentUser.setLoginIp(RequestIP.getIpAddr(request));
        currentUser.setRealName(user.getRealName());
        currentUser.setUserId(user.getUserId());
        currentUser.setUserType(user.getUserType());
        subject.getSession().setAttribute(AppContext.getAdminSessionKey(), currentUser);


        //更新最后一次登录的IP
        this.adminUserService.updateLastLoginInfo(currentUser);

        map.put("msg", "登录成功");
        map.put("success", true);

        return map;
    }

    /**
     * 后台树
     *
     * @return
     */
    @RequestMapping("/menu")
    @ResponseBody
    @RequiresUser
    public List<TreeNode> functionMenu() {
        Subject subject = SecurityUtils.getSubject();
        List<TreeNode> menuNodes = this.adminUserService.getAdminTreeNodes(subject);
        return menuNodes;
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping(value = "/logout")
    @RequiresUser
    public ModelAndView logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        HttpServletRequest request = RequestThread.getRequest();
        HttpServletResponse response = RequestThread.getResponse();
        request.getSession().invalidate();
        return new ModelAndView(new RedirectView("/admin/index.jsp", false));
    }

    /**
     * 修改密码
     *
     * @return
     */
    @RequestMapping(value = "/page_xgmm")
    @RequiresUser
    public ModelAndView page_xgmm() {
        Map<String, Object> map = new HashMap<String, Object>();
        return new ModelAndView("/admin/page_xgmm", map);
    }

    /**
     * 后台框架页面
     *
     * @return
     */
    @RequestMapping(value = "/frame")
    @RequiresUser
    public ModelAndView frame() {
        Map<String, Object> map = new HashMap<String, Object>();
        return new ModelAndView("/admin/frame", map);

    }


    /**
     * 后台框架页面
     *
     * @return
     */
    @RequestMapping(value = "/page_main")
    @RequiresUser
    public ModelAndView page_main() {
        Map<String, Object> map = new HashMap<String, Object>();
        return new ModelAndView("/admin/page_main", map);
    }

    /**
     * 保持在线状态
     */
    @RequestMapping(value = "/ping")
    public void ping() {
        // 什么都不做，只是为了保持session不过期
        //this.adminUserService.testTrasaction();
    }


    /**
     * 各模块的页面默认地址页面
     *
     * @param moduleId
     * @return
     */
    @RequestMapping(value = "/module_{moduleId}")
    public String modulePage(@PathVariable("moduleId") String moduleId) {
        return "/admin/" + moduleId.replaceAll("\\.", "/");
    }

    /**
     * 修改密码
     *
     * @param oldPassword
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping("/updatePwd")
    @AdminLog(module = MODULE_NAME, action = "修改密码")
    public Map<String, Object> updatePwd(
            String oldPassword, String password) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            this.adminUserService.updateUserPassword(CurrentUser.get().getUserId(), oldPassword, password);
            map.put("msg", "修改成功");
            map.put("success", true);
        } catch (Exception e) {
            log.error("修改密码出错", e);
            map.put("success", false);
            map.put("msg", e.getMessage());
        }

        return map;
    }


}
